<template>
  <div class="upload-container">
    <div class="upload-header">
      <div class="header-left">
        <h2><el-icon class="header-icon"><Document /></el-icon>文件上传</h2>
        <p class="header-desc">上传文件到知识库，支持PDF、Word、TXT等格式</p>
      </div>
      <el-select v-model="selectedKnowledge" placeholder="选择知识库" class="knowledge-select">
        <el-option
          v-for="item in knowledgeOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>
    
    <div class="upload-stats">
      <div class="stat-item">
        <div class="stat-icon">
          <el-icon><Files /></el-icon>
        </div>
        <div class="stat-info">
          <div class="stat-value">{{ fileList.length }}</div>
          <div class="stat-label">已选文件</div>
        </div>
      </div>
      <div class="stat-item">
        <div class="stat-icon">
          <el-icon><DocumentChecked /></el-icon>
        </div>
        <div class="stat-info">
          <div class="stat-value">{{ uploadedCount }}</div>
          <div class="stat-label">已上传文件</div>
        </div>
      </div>
    </div>
    
    <div class="upload-box">
      <el-upload
        class="upload-area"
        drag
        action="#"
        :auto-upload="false"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        :file-list="fileList"
        multiple
      >
        <div class="upload-content">
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            拖拽文件到此处或 <em>点击上传</em>
          </div>
          <div class="el-upload__tip">
            支持上传PDF、Word、TXT等文本文件，单个文件不超过10MB
          </div>
        </div>
      </el-upload>
    </div>
    
    <transition-group name="file-list" tag="div" class="file-list-container">
      <div v-for="(file, index) in fileList" :key="file.uid" class="file-item">
        <div class="file-info">
          <el-icon class="file-icon"><Document /></el-icon>
          <div class="file-details">
            <div class="file-name">{{ file.name }}</div>
            <div class="file-size">{{ formatFileSize(file.size) }}</div>
          </div>
        </div>
        <div class="file-actions">
          <el-tooltip content="预览文件" placement="top">
            <el-button circle size="small" @click="previewFile(file)">
              <el-icon><View /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="删除文件" placement="top">
            <el-button circle size="small" type="danger" @click="removeFile(index)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </el-tooltip>
        </div>
        <div v-if="uploadingFiles[file.uid]" class="file-progress">
          <el-progress :percentage="uploadingFiles[file.uid]" :stroke-width="4" />
        </div>
      </div>
    </transition-group>
    
    <div class="upload-actions" v-if="fileList.length > 0">
      <el-button type="primary" @click="submitUpload" :loading="uploading" class="upload-btn">
        <el-icon><Upload /></el-icon>开始上传
      </el-button>
      <el-button @click="clearFiles" :disabled="uploading">
        <el-icon><Delete /></el-icon>清空文件
      </el-button>
    </div>
    
    <el-dialog v-model="previewVisible" title="文件内容预览" width="60%" class="preview-dialog">
      <div class="file-preview">
        <p>{{ previewContent }}</p>
      </div>
    </el-dialog>
    
    <div v-if="fileList.length === 0 && !uploading" class="empty-upload">
      <el-icon><Upload /></el-icon>
      <p>暂无文件，请添加文件</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled, Document, Files, DocumentChecked, View, Delete, Upload } from '@element-plus/icons-vue'
import { getKnowledgeList, uploadKnowledgeFile } from '@/api/knowledge'

const selectedKnowledge = ref('')
const fileList = ref([])
const previewVisible = ref(false)
const previewContent = ref('')
const uploading = ref(false)
const uploadedCount = ref(0)
const uploadingFiles = reactive({})

// 知识库选项
const knowledgeOptions = ref([])

/**
 * 获取知识库列表
 * 从后端接口获取用户的知识库列表用于选择
 */
const fetchKnowledgeList = async () => {
  try {
    const response = await getKnowledgeList({
      page: 1,
      pageSize: 100 // 获取所有知识库，假设不超过100个
    })
    
    if (response.code === 1 && response.data && response.data.records) {
      // 将后端返回的知识库数据转换为下拉选项格式
      knowledgeOptions.value = response.data.records.map(item => ({
        value: item.knowledgeCode, // 使用知识库编码作为值
        label: item.knowledgeName  // 使用知识库名称作为显示标签
      }))
    } else {
      ElMessage({
        message: '获取知识库列表失败',
        type: 'error',
        customClass: 'custom-message'
      })
    }
  } catch (error) {
    console.error('获取知识库列表失败:', error)
    ElMessage({
      message: '获取知识库列表失败，请检查网络连接',
      type: 'error',
      customClass: 'custom-message'
    })
  }
}

// 组件挂载时获取知识库列表
onMounted(() => {
  fetchKnowledgeList()
})

// 格式化文件大小
const formatFileSize = (size) => {
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(1) + ' KB'
  } else {
    return (size / (1024 * 1024)).toFixed(1) + ' MB'
  }
}

// 处理文件变化
const handleFileChange = (file, uploadFileList) => {
  // 检查文件类型
  const allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/plain']
  if (!allowedTypes.includes(file.raw.type)) {
    ElMessage({
      message: '不支持的文件类型',
      type: 'error',
      customClass: 'custom-message'
    })
    return false
  }
  
  // 检查文件大小
  const maxSize = 10 * 1024 * 1024 // 10MB
  if (file.size > maxSize) {
    ElMessage({
      message: '文件大小不能超过10MB',
      type: 'error',
      customClass: 'custom-message'
    })
    return false
  }
  
  // 验证通过，更新响应式文件列表
  fileList.value = uploadFileList
  console.log('文件列表更新:', fileList.value.length)
  return true
}

// 处理文件移除
const handleFileRemove = (file) => {
  const index = fileList.value.findIndex(item => item.uid === file.uid)
  if (index !== -1) {
    fileList.value.splice(index, 1)
  }
}

// 移除文件
const removeFile = (index) => {
  if (index >= 0 && index < fileList.value.length) {
    fileList.value.splice(index, 1)
  }
}

// 提交上传
const submitUpload = async () => {
  if (!selectedKnowledge.value) {
    ElMessage({
      message: '请选择知识库',
      type: 'warning',
      customClass: 'custom-message'
    })
    return
  }
  
  if (fileList.value.length === 0) {
    ElMessage({
      message: '请选择要上传的文件',
      type: 'warning',
      customClass: 'custom-message'
    })
    return
  }
  
  uploading.value = true
  let successCount = 0
  let failCount = 0
  
  try {
    // 逐个上传文件
    for (let i = 0; i < fileList.value.length; i++) {
      const file = fileList.value[i]
      
      try {
        // 设置上传进度
        uploadingFiles[file.uid] = 0
        
        // 调用上传接口，传递文件对象和知识库编码
        await uploadKnowledgeFile(file.raw, selectedKnowledge.value)
        
        // 上传成功
        uploadingFiles[file.uid] = 100
        successCount++
        
        ElMessage({
          message: `文件 "${file.name}" 上传成功`,
          type: 'success',
          customClass: 'custom-message'
        })
        
      } catch (error) {
        console.error(`文件 "${file.name}" 上传失败:`, error)
        failCount++
        
        ElMessage({
          message: `文件 "${file.name}" 上传失败: ${error.message || '未知错误'}`,
          type: 'error',
          customClass: 'custom-message'
        })
      }
    }
    
    // 显示总体上传结果
    if (successCount > 0) {
      uploadedCount.value += successCount
      
      if (failCount === 0) {
        ElMessage({
          message: `成功上传 ${successCount} 个文件到知识库`,
          type: 'success',
          customClass: 'custom-message'
        })
      } else {
        ElMessage({
          message: `上传完成：成功 ${successCount} 个，失败 ${failCount} 个`,
          type: 'warning',
          customClass: 'custom-message'
        })
      }
    }
    
    // 清空文件列表
    fileList.value = []
    Object.keys(uploadingFiles).forEach(key => {
      delete uploadingFiles[key]
    })
    
  } catch (error) {
    console.error('上传过程中发生错误:', error)
    ElMessage({
      message: '上传过程中发生错误，请重试',
      type: 'error',
      customClass: 'custom-message'
    })
  } finally {
    uploading.value = false
  }
}

// 清空文件列表
const clearFiles = () => {
  if (uploading.value) return
  
  if (fileList.value.length > 0) {
    ElMessageBox.confirm('确认清空所有文件？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      fileList.value = []
    }).catch(() => {})
  }
}

// 预览文件内容
const previewFile = (file) => {
  // 模拟文件内容预览
  previewContent.value = `这是文件 ${file.name} 的内容预览...\n\n${Array(20).fill('示例内容行 ' + file.name).join('\n')}`
  previewVisible.value = true
}
</script>

<style scoped>
.upload-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.upload-container::-webkit-scrollbar {
  width: 6px;
}

.upload-container::-webkit-scrollbar-thumb {
  background-color: var(--el-color-primary-light-5);
  border-radius: 3px;
}

.upload-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.header-left {
  display: flex;
  flex-direction: column;
}

.header-left h2 {
  display: flex;
  align-items: center;
  font-size: 22px;
  margin: 0;
  color: var(--el-color-primary);
}

.header-icon {
  margin-right: 8px;
  font-size: 24px;
}

.header-desc {
  margin: 5px 0 0;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.knowledge-select {
  width: 200px;
}

/* 统计项样式 */
.upload-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-item {
  flex: 1;
  display: flex;
  align-items: center;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.stat-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  border-radius: 8px;
  background: var(--el-color-primary-light-8);
  margin-right: 15px;
}

.stat-icon .el-icon {
  font-size: 24px;
  color: var(--el-color-primary);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--el-color-primary-dark-2);
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

/* 上传区域样式 */
.upload-box {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.upload-box:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.upload-area {
  width: 100%;
}

.upload-content {
  padding: 30px 0;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: auto;
  padding: 20px;
  border: 2px dashed var(--el-color-primary-light-5);
  transition: all 0.3s;
}

:deep(.el-upload-dragger:hover) {
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}

:deep(.el-icon--upload) {
  font-size: 48px;
  color: var(--el-color-primary);
  margin-bottom: 10px;
}

:deep(.el-upload__text) {
  font-size: 16px;
  margin-bottom: 10px;
}

:deep(.el-upload__text em) {
  color: var(--el-color-primary);
  font-style: normal;
  font-weight: bold;
}

:deep(.el-upload__tip) {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

/* 文件列表样式 */
.file-list-container {
  margin-bottom: 20px;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 10px;
  position: relative;
  transition: all 0.3s;
}

.file-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.file-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.file-icon {
  font-size: 24px;
  color: var(--el-color-primary);
  margin-right: 15px;
}

.file-details {
  flex: 1;
}

.file-name {
  font-weight: bold;
  margin-bottom: 5px;
  color: var(--el-text-color-primary);
}

.file-size {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.file-actions {
  display: flex;
  gap: 10px;
}

.file-progress {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 0 15px 5px;
}

/* 文件列表动画 */
.file-list-enter-active,
.file-list-leave-active {
  transition: all 0.5s ease;
}

.file-list-enter-from,
.file-list-leave-to {
  opacity: 0;
  transform: translateY(30px);
}

/* 上传按钮样式 */
.upload-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

.upload-btn {
  background: var(--el-color-primary);
  transition: all 0.3s;
}

.upload-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 空状态样式 */
.empty-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
  color: var(--el-text-color-secondary);
}

.empty-upload .el-icon {
  font-size: 48px;
  margin-bottom: 15px;
  color: var(--el-color-info-light-5);
}

/* 预览对话框样式 */
:deep(.preview-dialog .el-dialog__header) {
  background: var(--el-color-primary-light-9);
  margin: 0;
  padding: 15px 20px;
}

:deep(.preview-dialog .el-dialog__title) {
  color: var(--el-color-primary-dark-2);
  font-weight: bold;
}

.file-preview {
  max-height: 400px;
  overflow-y: auto;
  white-space: pre-wrap;
  font-family: monospace;
  padding: 15px;
  background: #f8f8f8;
  border-radius: 4px;
}

/* 消息提示自定义样式 */
:deep(.custom-message) {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
</style>